"""
文档处理器
负责处理各种格式的合同文档，提取文本内容
"""

import os
import logging
from pathlib import Path
from typing import Optional, Dict, Any
import chardet

try:
    import PyPDF2
    import pdfplumber
except ImportError:
    PyPDF2 = None
    pdfplumber = None

try:
    from docx import Document
except ImportError:
    Document = None

from config import Config

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class DocumentProcessor:
    """文档处理器类"""
    
    def __init__(self):
        """初始化文档处理器"""
        self.config = Config()
        
    def extract_content(self, file_path: str) -> Dict[str, Any]:
        """
        从文档中提取内容
        
        Args:
            file_path: 文件路径
            
        Returns:
            包含提取内容的字典
        """
        file_path = Path(file_path)
        
        if not file_path.exists():
            raise FileNotFoundError(f"文件不存在: {file_path}")
        
        # 检查文件大小
        if file_path.stat().st_size > self.config.MAX_FILE_SIZE:
            raise ValueError(f"文件过大，超过限制: {self.config.MAX_FILE_SIZE / 1024 / 1024}MB")
        
        # 根据文件扩展名选择处理方法
        extension = file_path.suffix.lower()
        
        if extension == '.pdf':
            return self._extract_from_pdf(file_path)
        elif extension in ['.docx', '.doc']:
            return self._extract_from_word(file_path)
        elif extension == '.txt':
            return self._extract_from_txt(file_path)
        else:
            raise ValueError(f"不支持的文件格式: {extension}")
    
    def _extract_from_pdf(self, file_path: Path) -> Dict[str, Any]:
        """从PDF文件提取内容"""
        if not pdfplumber:
            raise ImportError("需要安装pdfplumber库: pip install pdfplumber")
        
        content = ""
        metadata = {}
        
        try:
            # 使用pdfplumber提取文本（更准确）
            with pdfplumber.open(file_path) as pdf:
                metadata = {
                    "pages": len(pdf.pages),
                    "title": pdf.metadata.get('Title', ''),
                    "author": pdf.metadata.get('Author', ''),
                    "creator": pdf.metadata.get('Creator', '')
                }
                
                for page in pdf.pages:
                    page_text = page.extract_text()
                    if page_text:
                        content += page_text + "\n"
        
        except Exception as e:
            logger.warning(f"pdfplumber提取失败，尝试PyPDF2: {e}")
            
            # 备用方案：使用PyPDF2
            if PyPDF2:
                try:
                    with open(file_path, 'rb') as file:
                        pdf_reader = PyPDF2.PdfReader(file)
                        metadata["pages"] = len(pdf_reader.pages)
                        
                        for page in pdf_reader.pages:
                            content += page.extract_text() + "\n"
                except Exception as e2:
                    raise Exception(f"PDF处理失败: {e2}")
            else:
                raise Exception(f"PDF处理失败，请安装相关库: {e}")
        
        return {
            "content": content.strip(),
            "metadata": metadata,
            "file_type": "pdf"
        }
    
    def _extract_from_word(self, file_path: Path) -> Dict[str, Any]:
        """从Word文档提取内容"""
        if not Document:
            raise ImportError("需要安装python-docx库: pip install python-docx")
        
        try:
            doc = Document(file_path)
            
            # 提取段落文本
            content = ""
            for paragraph in doc.paragraphs:
                content += paragraph.text + "\n"
            
            # 提取表格文本
            for table in doc.tables:
                for row in table.rows:
                    for cell in row.cells:
                        content += cell.text + " "
                    content += "\n"
            
            # 获取文档属性
            metadata = {
                "paragraphs": len(doc.paragraphs),
                "tables": len(doc.tables),
                "title": doc.core_properties.title or "",
                "author": doc.core_properties.author or "",
                "created": str(doc.core_properties.created) if doc.core_properties.created else ""
            }
            
            return {
                "content": content.strip(),
                "metadata": metadata,
                "file_type": "word"
            }
            
        except Exception as e:
            raise Exception(f"Word文档处理失败: {e}")
    
    def _extract_from_txt(self, file_path: Path) -> Dict[str, Any]:
        """从文本文件提取内容"""
        try:
            # 检测文件编码
            with open(file_path, 'rb') as file:
                raw_data = file.read()
                encoding_result = chardet.detect(raw_data)
                encoding = encoding_result['encoding'] or 'utf-8'
            
            # 读取文件内容
            with open(file_path, 'r', encoding=encoding) as file:
                content = file.read()
            
            # 统计信息
            lines = content.split('\n')
            metadata = {
                "lines": len(lines),
                "characters": len(content),
                "encoding": encoding,
                "confidence": encoding_result['confidence']
            }
            
            return {
                "content": content.strip(),
                "metadata": metadata,
                "file_type": "text"
            }
            
        except Exception as e:
            raise Exception(f"文本文件处理失败: {e}")
    
    def validate_content(self, content: str) -> bool:
        """
        验证提取的内容是否有效
        
        Args:
            content: 提取的文本内容
            
        Returns:
            是否有效
        """
        if not content or len(content.strip()) < 10:
            return False
        
        # 检查是否包含合同相关关键词
        contract_keywords = [
            "合同", "协议", "甲方", "乙方", "条款", "责任", 
            "违约", "终止", "签署", "生效", "履行"
        ]
        
        content_lower = content.lower()
        keyword_count = sum(1 for keyword in contract_keywords if keyword in content_lower)
        
        # 至少包含2个合同相关关键词
        return keyword_count >= 2
    
    def get_content_summary(self, content: str) -> Dict[str, Any]:
        """
        获取内容摘要信息
        
        Args:
            content: 文本内容
            
        Returns:
            摘要信息
        """
        lines = content.split('\n')
        words = content.split()
        
        return {
            "total_lines": len(lines),
            "total_words": len(words),
            "total_characters": len(content),
            "non_empty_lines": len([line for line in lines if line.strip()]),
            "average_line_length": sum(len(line) for line in lines) / len(lines) if lines else 0
        }
